package cn.ctwing.ws.client.impl;

import cn.ctwing.ws.client.api.IAuth;

public class WSAuth implements IAuth {

	@Override
	public String genWsURI(String host, String appKey, String appSecret) {
		return join(host,"/ws-push/",appKey,"/",token(appSecret));
	}
	
	
	/**
	 * 生成令牌
	 * @param secret 密钥
	 * @return 令牌
	 */
	private String token(String secret) {
		String time =unixTime();
		String random =Tokens.randomString(8);
		return join(time,".",random,".",sgin(time,random,secret));
	}
	
	/**
	 * 连接字符
	 * @param str 字符
	 * @return 连接结果
	 */
	private String join(String ...str) {
		StringBuilder sb = new StringBuilder();
		for(String s :str) {
			sb.append(s);
		}
		return sb.toString();
	}
	
	/**
	 * UNIX时间戳
	 * @return UNIX时间戳
	 */
	private String unixTime() {
		return String.valueOf(System.currentTimeMillis()/100);
	}
	
	/**
	 * 
	 * @param time UNIX时间戳
	 * @param random 随机数
	 * @param secret 密钥
	 * @return
	 */
	private String sgin(String time,String random,String secret) {
		return sha256Hex(time+random+secret);
	}
	
	/**
	 * 
	 * @param str SHA256
	 * @return SHA256HEX
	 */
	private String sha256Hex(String str) {
		Sha256 hash = new Sha256();
		byte[] hbytes = hash.sum(str.getBytes());
		return Bytes.toHexString(hbytes);
	}

}
